package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;

@RestController
@RequestMapping("/emps")
@Slf4j
public class EmpController {

    @Autowired
    private EmpService empService;
     /*
       ?page=1&pageSize=10
        直接接收
          @RequestParam()  表示必填的参数
            defaultValue = "1" 默认值是1
          @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")
          这两个值是必有数据字段，如果没有使用默认值
      */
    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize,
                       String name, Short gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd")LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd")LocalDate end){
        log.info("需要查询的页码是:"+page+"  需要查询的每页数据条数是:"+pageSize);
        // 需要把 页码和每页条数 传递给service 由service 完成 PageBean的封装
        PageBean pb = empService.page(page,pageSize,name,gender,begin,end);
        return Result.success(pb);
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable Integer[] ids){
        log.info("接收到的数组数据是："+ Arrays.toString(ids));
        //交给service批量删除
        empService.delete(ids);

        return Result.success();
    }

    @PostMapping
    public Result save(@RequestBody Emp emp){
        log.info("添加的员工信息:{}",emp);
        //找 service完成添加
        empService.add(emp);//emp里面没有id  没有时间

        return Result.success();
    }


    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        log.info("查询的员工id是:"+id);
        //找service 根据id 查询一个员工
        Emp emp = empService.getById(id);
        return Result.success(emp);
    }

    @PutMapping
    public Result update(@RequestBody Emp emp){
        log.info("要修改的emp:{}",emp);
        //找 service
        empService.update(emp);
        return Result.success();
    }
}
